package com.demo.java.service.impl;

import com.demo.java.model.entity.Person;
import com.demo.java.model.params.Query;
import com.demo.java.service.RedisCacheService;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class RedisCacheServiceImpl implements RedisCacheService {

    public static final Map<String, Person> maps = Maps.newHashMap();

    static {
        maps.put("zhangsan", Person.builder().name("zhangsan").address("beijing").build());
        maps.put("lisi", Person.builder().name("lisi").address("wuhan").build());
        maps.put("wangwu", Person.builder().name("wangwu").address("chongqin").build());
        maps.put("xiaoxin", Person.builder().name("xiaoxin").address("guangzhou").build());
        maps.put("java", Person.builder().name("java").address("shanghai").build());
    }

    // 缓存的key = catalog::key
    @Cacheable(key = "#root.args[0].key", value = "catalog")
    public Person getCache(Query query) {
        log.info("get cache");
        if (maps.containsKey(query.getKey())) {
            return maps.get(query.getKey());
        }
        return null;
    }

    // 清除缓存测试
    @CacheEvict(value = "catalog", key = "#root.args[0].key")
    public boolean update(Query query) {
        if (StringUtils.isEmpty(query.getAddress())) {
            return false;
        }
        if (maps.containsKey(query.getKey())) {
            maps.get(query.getKey()).setAddress(query.getAddress());
            return true;
        }
        return false;
    }
}
